package com.ebraga.trackerclub.android.view;

import java.util.ArrayList;

import android.app.Fragment;
import android.app.FragmentManager;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;

import com.ebraga.trackerclub.android.R;
import com.ebraga.trackerclub.android.util.ISmartServiceConstants;
import com.ebraga.trackerclub.android.util.UtilView;
import com.ebraga.trackerclub.android.view.adapter.NavDrawerListAdapter;
import com.ebraga.trackerclub.android.view.fragment.CheckInOutFragment;
import com.ebraga.trackerclub.android.view.fragment.ChronometerFragment;
import com.ebraga.trackerclub.android.view.fragment.MainFragment;
import com.ebraga.trackerclub.android.view.fragment.RankingFragment;
import com.ebraga.trackerclub.android.vo.NavDrawerItemVo;

public class MainActivity extends GpsActivity {
    private DrawerLayout mDrawerLayout;
    private ListView mDrawerList;
    private ActionBarDrawerToggle mDrawerToggle;

    private CharSequence mDrawerTitle;
    private CharSequence mTitle;
    
    private String[] menuItens;
    private TypedArray navMenuIcons;
    
    private ArrayList<NavDrawerItemVo> navDrawerItems;
    
    private boolean doubleBackToExitPressedOnce = false;     
    
    //First Screen
    private String currentScreen = ISmartServiceConstants.SCREEN_TAG.CHECKINOUT;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mTitle = mDrawerTitle = getTitle();
        menuItens = getResources().getStringArray(R.array.nav_drawer_items);
        // nav drawer icons from resources
        navMenuIcons = getResources().obtainTypedArray(R.array.nav_drawer_icons);
        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        mDrawerList = (ListView) findViewById(R.id.left_drawer);

        // set a custom shadow that overlays the main content when the drawer opens
        mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
        
        navDrawerItems = new ArrayList<NavDrawerItemVo>();
        
        // adding nav drawer items to array
        //Mapa
        navDrawerItems.add(new NavDrawerItemVo(menuItens[0], navMenuIcons.getResourceId(0, -1)));
        
        //Ranking
        navDrawerItems.add(new NavDrawerItemVo(menuItens[1], navMenuIcons.getResourceId(1, -1)));

        //Chronometer
        navDrawerItems.add(new NavDrawerItemVo(menuItens[2], navMenuIcons.getResourceId(2, -1)));        
        
        /* PRIMEIRA VERSÃO TEM APENAS CHECK IN
        
        //Menu Chamados
        navDrawerItems.add(new NavDrawerItemVo(menuItens[1], navMenuIcons.getResourceId(1, -1), true, "5"));
        //Menu Lacres
        navDrawerItems.add(new NavDrawerItemVo(menuItens[2], navMenuIcons.getResourceId(2, -1), true, "2"));
        //Menu Monitoração
        navDrawerItems.add(new NavDrawerItemVo(menuItens[3], navMenuIcons.getResourceId(3, -1)));
        //Menu Peças
        navDrawerItems.add(new NavDrawerItemVo(menuItens[4], navMenuIcons.getResourceId(4, -1)));
        //Menu Configurações
        navDrawerItems.add(new NavDrawerItemVo(menuItens[5], navMenuIcons.getResourceId(5, -1)));
        //Menu Incidentes
        navDrawerItems.add(new NavDrawerItemVo(menuItens[6], navMenuIcons.getResourceId(6, -1)));    
        
            */
        
        // Recycle the typed array
        navMenuIcons.recycle();
        
        // set up the drawer's list view with items and click listener
        mDrawerList.setAdapter(new NavDrawerListAdapter(getApplicationContext(), navDrawerItems));
        
        mDrawerList.setOnItemClickListener(new DrawerItemClickListener());

        // enable ActionBar app icon to behave as action to toggle nav drawer
        getActionBar().setDisplayHomeAsUpEnabled(true);
        getActionBar().setHomeButtonEnabled(true);

        // ActionBarDrawerToggle ties together the the proper interactions
        // between the sliding drawer and the action bar app icon
        mDrawerToggle = new ActionBarDrawerToggle(
                this,                  /* host Activity */
                mDrawerLayout,         /* DrawerLayout object */
                R.drawable.ic_drawer,  /* nav drawer image to replace 'Up' caret */
                R.string.drawer_open,  /* "open drawer" description for accessibility */
                R.string.drawer_close  /* "close drawer" description for accessibility */
                ) {
            public void onDrawerClosed(View view) {
                getActionBar().setTitle(mTitle);
                invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
            }

            public void onDrawerOpened(View drawerView) {
                getActionBar().setTitle(mDrawerTitle);
                invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
            }
        };
        mDrawerLayout.setDrawerListener(mDrawerToggle);

        if (savedInstanceState == null) {
            selectItem(0);
        }
        
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.main, menu);
        return super.onCreateOptionsMenu(menu);
    }

    /* Called whenever we call invalidateOptionsMenu() */
    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        // If the nav drawer is open, hide action items related to the content view
        //boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
        //menu.findItem(R.id.action_logout).setVisible(!drawerOpen);
        return super.onPrepareOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
         // The action bar home/up action should open or close the drawer.
         // ActionBarDrawerToggle will take care of this.
        if (mDrawerToggle.onOptionsItemSelected(item)) {
            return true;
        } else if (item.getTitle().equals(getString(R.string.action_logout))) {
   			super.finish();
   			onDestroy();
   			return true;
        }

        return super.onOptionsItemSelected(item);

    }

    /* The click listner for ListView in the navigation drawer */
    private class DrawerItemClickListener implements ListView.OnItemClickListener {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            selectItem(position);
        }
    }

    private void selectItem(int position) {
    	Fragment fragment;
    	
    	if (position == 0) {
    		fragment = new CheckInOutFragment();
    	} else if (position == 1) {
        		fragment = new RankingFragment();  
    	} else if (position == 2) { 
    		fragment = new ChronometerFragment();    		
    	} else {
	        // update the main content by replacing fragments
	        fragment = new MainFragment();
    	}
    	
        Bundle args = new Bundle();
        args.putInt(MainFragment.ARG_MENU_ITENS, position);
        fragment.setArguments(args);

        FragmentManager fragmentManager = getFragmentManager();
        fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();    	

        // update selected item and title, then close the drawer
        mDrawerList.setItemChecked(position, true);
        
        Resources res = getResources();
        
        //Agrega nome do menu ao titulo.
        //setTitle(res.getString(R.string.app_name) + " - " + menuItens[position]);
        
        setTitle(res.getString(R.string.app_name));
        mDrawerLayout.closeDrawer(mDrawerList);
    }

	@SuppressWarnings("unused")
	private void menuUnread() {
		//Metodo para atualizar itens não vistos.
		
		navDrawerItems.set(1, new NavDrawerItemVo(menuItens[1], navMenuIcons.getResourceId(1, -1), true, "15"));

		// Recycle the typed array
		navMenuIcons.recycle();
		
		// set up the drawer's list view with items and click listener
		mDrawerList.setAdapter(new NavDrawerListAdapter(getApplicationContext(), navDrawerItems));
	}

    @Override
    public void setTitle(CharSequence title) {
        mTitle = title;
        getActionBar().setTitle(mTitle);
    }

    /**
     * When using the ActionBarDrawerToggle, you must call it during
     * onPostCreate() and onConfigurationChanged()...
     */

    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        // Sync the toggle state after onRestoreInstanceState has occurred.
        mDrawerToggle.syncState();
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        // Pass any configuration change to the drawer toggls
        mDrawerToggle.onConfigurationChanged(newConfig);
    }

       @Override
    public void onDestroy() {
        super.onDestroy();
    }


   	@Override
   	/**
   	 * Controla botão voltar do Android para evitar saída da aplicação por engano.
   	 */
   	public void onBackPressed() {
   		
   		if (getCurrentScreen() == null || getCurrentScreen().equals(ISmartServiceConstants.SCREEN_TAG.CHECKINOUT)) {
   		
	   		if (doubleBackToExitPressedOnce) {
	   			super.finish();
	   			onDestroy();
	   			return;
	   		}
	   		this.doubleBackToExitPressedOnce = true;
	   		
	   		UtilView.showMessage(getBaseContext(), getString(R.string.back_twice));
	   		
	   		//Toast.makeText(this, getString(R.string.back_twice),Toast.LENGTH_SHORT).show();
	   		
	   		new Handler().postDelayed(new Runnable() {
	
	   			@Override
	   			public void run() {
	   				doubleBackToExitPressedOnce = false;
	
	   			}
	   		}, 5000);
   		
   		} else if (getCurrentScreen().equals(ISmartServiceConstants.SCREEN_TAG.CHECKINOUT_HISTORY)) {
   			selectItem(0);
   		}
   	}

	public String getCurrentScreen() {
		return currentScreen;
	}

	public void setCurrentScreen(String currentScreen) {
		this.currentScreen = currentScreen;
	}   	       
       
   		
}